package avicit.tlk.back.demo.my111.service;

import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.commons.utils.*;
import avicit.platform6.core.common.baseservice.BaseService;
import avicit.platform6.core.excel.ExcelUtil;
import avicit.platform6.core.excel.Map2Bo;
import avicit.platform6.core.excel.imp.entity.ExcelImportResult;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryReqBean;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import avicit.tlk.back.demo.my111.dao.My111DAO;
import avicit.tlk.back.demo.my111.dto.My111DTO;
import avicit.tlk.back.demo.my111.dto.My111ImportDTO;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * My111Service类
 *
 * @author 朱辉云
 * @version 1.0.0
 * @date 2025-06-13 10:23:55
 * @since 1.0.0
 */
@Service
public class My111Service extends BaseService<My111DAO, My111DTO> {

	private static final Logger logger = LoggerFactory.getLogger(My111Service.class);

	@Autowired
	private My111DAO my111DAO;

	@Autowired
	private ConvertColumnClient convertColumnClient;

	/**
	 * 按条件分页查询数据
	 *
	 * @param queryReqBean 查询条件
	 * @return 满足分页条件的数据
	 */
	@Transactional(readOnly = true)
	public QueryRespBean<My111DTO> findListByPage(QueryReqBean<My111DTO> queryReqBean) {
		QueryRespBean<My111DTO> queryRespBean = new QueryRespBean<>();
		List<My111DTO> result = super.findByPage(queryReqBean);
		this.valueConvert(result);
		queryRespBean.setResultByList(result);
		return queryRespBean;
	}

	/**
	 * 按条件查询数据
	 *
	 * @param queryReqBean 查询条件
	 * @return 满足条件的数据
	 */
	@Transactional(readOnly = true)
	public List<My111DTO> findList(QueryReqBean<My111DTO> queryReqBean) {
		My111DTO searchParams = super.getQueryEntity(queryReqBean);
		List<My111DTO> result = super.findList(searchParams);
		this.valueConvert(result);
		return result;
	}

	/**
	 * 根据主键查询数据
	 *
	 * @param id 主键
	 * @return 主键对应的数据
	 */
	@Transactional(readOnly = true)
	@Override
	public My111DTO get(String id) {
		My111DTO result = super.get(id);
		if (result != null) {
			this.valueConvert(Arrays.asList(result));
		}
		return result;
	}

	/**
	 * 新增数据
	 *
	 * @param entity 表单数据
	 * @return 主键
	 */
	@Transactional
	@Override
	public String insert(My111DTO entity) {
		entity.setId(ComUtil.getId());
		String id = super.insert(entity);
		return id;
	}

	/**
	 * 批量新增数据
	 *
	 * @param entities 新增的数据列表
	 * @return 受影响的行数
	 */
	@Transactional
	@Override
	public int insertBatch(List<My111DTO> entities) {
		for (My111DTO entity : entities) {
			String id = ComUtil.getId();
			entity.setId(id);
		}
		int count = super.insertBatch(entities);
		return count;
	}

	/**
	 * 修改对象全部字段
	 *
	 * @param entity 修改对象
	 * @return 受影响的行数
	 */
	@Transactional
	@Override
	public int updateAll(My111DTO entity) {
		if (entity == null) {
			throw new BusinessException("修改对象不能为空！");
		}
		if (StringUtils.isEmpty(entity.getId())) {
			throw new BusinessException("修改对象的Id不能为空！");
		}
		int count = super.updateAll(entity);
		return count;
	}

	/**
	 * 修改对象部分数据
	 *
	 * @param entity 表单数据
	 * @return 受影响的行数
	 */
	@Transactional
	@Override
	public int updateSensitive(My111DTO entity) {
		if (entity == null) {
			throw new BusinessException("修改对象不能为空！");
		}
		if (StringUtils.isEmpty(entity.getId())) {
			throw new BusinessException("修改对象的id不能为空！");
		}
		return super.updateSensitive(entity);
	}

	/**
	 * 批量更新数据
	 *
	 * @param entities 更新的的数据列表
	 * @return 受影响的行数
	 */
	@Transactional
	@Override
	public int updateBatch(List<My111DTO> entities) {
		return super.updateBatch(entities);
	}

	/**
	 * 按主键单条删除数据
	 *
	 * @param id 主键
	 * @return 受影响的行数
	 */
	@Transactional
	@Override
	public int delete(String id) {
		int count = super.delete(id);
		return count;
	}

	/**
	 * 按主键批量删除数据
	 *
	 * @param ids 主键数组
	 * @return 受影响的行数
	 */
	@Transactional
	@Override
	public int deleteByIds(String[] ids) {
		int count = super.deleteByIds(ids);
		return count;
	}

	/**
	 * 日志专用，内部方法，不再记录日志
	 *
	 * @param id 主键id
	 * @return 数据
	 */
	private My111DTO findById(String id) {
		return super.get(id);
	}

	/**
	 * 数据导入
	 *
	 * @param entities 导入数据集合
	 * @param formData 表单参数
	 * @return 导入结果
	 */
	@Transactional
	public ExcelImportResult importData(List<Map<String, String>> entities, String formData) {
		List<My111DTO> succesResult = new ArrayList<My111DTO>();
		List<My111ImportDTO> errorResult = new ArrayList<My111ImportDTO>();
		Map<String, Object> formDataMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(formData)) {
			formDataMap = JsonUtil.parseJSON2Map(formData);
		}
		if (!CollectionUtils.isEmpty(entities)) {
			Map<String, Map<String, String>> convertResultData = this.assembleData(entities);
			for (Map<String, String> data : entities) {
				if (StringUtils.isEmpty(data.get("errorInfo"))) {
					My111DTO dto = new My111DTO();
					Map2Bo.map2Pojo(data, dto);
					succesResult.add(dto);
				} else {
					My111ImportDTO dtoImp = new My111ImportDTO();
					Map2Bo.map2Pojo(data, dtoImp);
					errorResult.add(dtoImp);
				}
			}
			this.revValueConvert(succesResult, convertResultData);
			this.insertBatch(succesResult);
		}
		ExcelImportResult excelImport = ExcelUtil.createUploadHis(succesResult, errorResult, My111ImportDTO.class, formDataMap);
		SysLogUtil.log(
			new My111DTO().getLogTitle(),
			new My111DTO().getLogTitle() + "共导入" + excelImport.getTotalRecord() + "条,导入成功" + excelImport.getSuccessRecord() + "条,导入失败" + excelImport.getFailRecord() + "条。",
			PlatformConstant.OpType.fileImport,
			PlatformConstant.OpResult.success,
			ComUtil.getId(),
			"my111"
		);
		return excelImport;
	}

	/**
	 * 将属性值(ID)转为名称，
	 *
	 * @param entities 转换的数据集合
	 * @apiNote 包括：用户、角色、部门、岗位、群组、通用代码
	 */
	private void valueConvert(List<My111DTO> entities) {
		Map<String, Set<String>> convertFormData = new HashMap<>();
		for (My111DTO temp : entities) {
			BusinessUtil.createConvertSet(convertFormData, "PLATFORM_FILE_SECRET_LEVEL", temp.getSecretLevel());
		}
		if (convertFormData.size() > 0) {
			Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
			for (My111DTO temp : entities) {
				temp.setSecretLevelName(BusinessUtil.convertFormat(convertResultData, "PLATFORM_FILE_SECRET_LEVEL", temp.getSecretLevel()));
			}
		}
	}

	/**
	 * 将属性名称转为ID
	 *
	 * @param entities          转换的数据集合
	 * @param convertResultData 需转换的结果值集合
	 * @apiNote 包含：用户、角色、部门、岗位、群组、通用代码
	 */
	private void revValueConvert(List<My111DTO> entities, Map<String, Map<String, String>> convertResultData) {
		for (My111DTO temp : entities) {
			temp.setSecretLevel(BusinessUtil.convertFormat(convertResultData, "PLATFORM_FILE_SECRET_LEVEL", temp.getSecretLevelName()));
		}
	}

	/**
	 * 将需转换的数据转为请求集合
	 *
	 * @param entities 数据集合
	 * @return 转换后的请求集合
	 * @apiNote 包含：用户、角色、部门、岗位、群组、通用代码
	 */
	private Map<String, Map<String, String>> assembleData(List<Map<String, String>> entities) {
		Map<String, Set<String>> convertFormData = new HashMap<>();
		for (Map<String, String> data : entities) {
			BusinessUtil.createConvertSet(convertFormData, "PLATFORM_FILE_SECRET_LEVEL", data.get("secretLevelName"));
		}
		return convertColumnClient.convertCodeToId(convertFormData);
	}
}
